<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />

	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'
import { getUserProfile, getUserSalary } from "@/api/system/user/profile";
import { OfficeequipmentrepairApi, OfficeRequisitionVO } from '@/api/oa/Officeequipmentrepair'
import { useMessage, useToast } from 'wot-design-uni'
import { useUserStore } from '@/store/modules/user';
import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'


const store = useUserStore();
const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const auditForm = ref() // 表单 Ref
const detailId = ref(null)
const resubmit = ref(0)
const fileList = ref([]) // 文件列表
const data = ref({ path: '' })
const defaulTimetValue = ref<number>(Date.now())

const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)

// 指定审批人
const processDefineKey = 'oa_officeequipmentrepair' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const userList = ref<any[]>([]) // 用户列表
const depList = ref<any[]>([]) // 部门列表
const sealList = ref<any[]>([])

// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	url: []
})
//表单项字段配置
const formFields = ref<any[]>([
	{
		type: 'input',
		prop: 'title',
		label: '标题',
		placeholder: '请输入标题'
	},
	{
		type: 'textarea',
		prop: 'specify',
		label: '具体情况',
		placeholder: '请输入具体情况'
	},
	{
		type: 'select',
		prop: 'userId',
		label: '申请人',
		placeholder: '请选择申请人',
		readonly: true,
		filterable: true,
		options: () => userList.value, // 需要你在渲染组件时用 userList 数据
		labelKey: 'nickname',
		valueKey: 'id',
		onChange: (val: any) => {
			console.log('val', val);
			const selectedUser = userList.value.find(user => user.id === val.value)
			if (selectedUser) {
				formData.value.userName = selectedUser.nickname
			}
		}
	},
	{
		type: 'select',
		prop: 'userDeptId',
		label: '申请部门',
		placeholder: '请选择申请部门',
		filterable: true,
		readonly: true,
		options: () => depList.value,
		labelKey: 'name',
		valueKey: 'id',
		onChange: (val: any) => {
			const selectedDep = depList.value.find(user => user.id === val.value)
			if (selectedDep) {
				formData.value.userDept = selectedDep.name
			}
		}

	},
	{
		type: 'datetime',
		prop: 'applicationTime',
		label: '申请时间',
		placeholder: '选择申请时间',
		datetimeType: 'date',
		// handleConfirm: ({ value }: { value: any }) => {
		// 	formData.value.applicationTime = formatDate(value)

		// }
		// datetimeType: 'date'
	},
	{
		type: 'input',
		prop: 'equipmentNun',
		label: '设备数',
		placeholder: '请输入设备数'
	},
	{
		type: 'select',
		prop: 'maintenanceType',
		label: '维修类型',
		placeholder: '请选择维修类型',
		options: [
			{ label: '维修', value: 1 },
			{ label: '更换', value: 2 },
			{ label: '其他', value: 3 }
		]
	},
	{
		type: 'upload', prop: 'url', label: '附件', placeholder: '请输入附件',
		action: globalConfig.uploadUrl,
		limit: 1,
		accept: 'all',
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'url',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},
	// {
	// 	type: 'input',
	// 	prop: 'departmentLeader',
	// 	label: '部门主管领导',
	// 	placeholder: '请输入部门主管领导'
	// },
	// {
	// 	type: 'input',
	// 	prop: 'sofficeKeeper',
	// 	label: '办公室内勤人员',
	// 	placeholder: '请输入办公室内勤人员'
	// },
	// {
	// 	type: 'input',
	// 	prop: 'officeManager',
	// 	label: '办公室采购员',
	// 	placeholder: '请输入办公室采购员'
	// },
	// {
	// 	type: 'input',
	// 	prop: 'officeLeader',
	// 	label: '办公室主任',
	// 	placeholder: '请输入办公室主任'
	// },
	{
		type: 'textarea',
		prop: 'remark',
		label: '备注',
		placeholder: '请输入备注'
	}
])//表单项字段配置
const formData = ref<OfficeRequisitionVO>({
} as any)
const formRules = reactive({
	title: [
		{ required: true, message: '请输入标题', trigger: 'blur' }
	],
	specify: [
		{ required: true, message: '请输入具体情况', trigger: 'blur' }
	],
	userId: [
		{ required: true, message: '请选择申请人', trigger: 'change' }
	],
	userDeptId: [
		{ required: true, message: '请选择申请部门', trigger: 'change' }
	],
	applicationTime: [
		{ required: true, message: '请选择申请时间', trigger: 'change' }
	],
	equipmentNun: [
		{ required: true, message: '请输入设备数', trigger: 'blur' },
		{
			validator: (value: any) => {
				if (value === '' || value === null || value === undefined) {
					return Promise.reject('请输入设备数')
				}
				const num = Number(value)
				if (isNaN(num) || num <= 0) {
					return Promise.reject('设备数必须为大于0的数字')
				}
				return Promise.resolve()
			},
			trigger: ['blur', 'change']
		}
	],
	maintenanceType: [
		{ required: true, message: '请选择维修类型', trigger: 'change' }
	]
})


onLoad(async (options) => {
	formData.value.userId = store.user.id
	formData.value.userName = store.user.nickname
	formData.value.userDeptId = store.user.deptId
	formData.value.userDept = store.user.deptName
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
	// 加载用户列表
	getUserList()
	//加载部门列表
	getDeptList()
})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await OfficeequipmentrepairApi.getOfficeequipmentrepair(Number(detailId.value))
		formData.value = data
		if (formData.value.applicationTime) {
			formData.value.applicationTime = parseDateToTimestamp(formData.value.applicationTime)
		}
		// 附件字段回显
		fileLists.value.url = buildFileList(data.url) as any;
		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}
/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();

	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
/** 获取部门列表 */
const getDeptList = async () => {
	try {
		depList.value = await DeptApi.getSimpleDeptList();

	} catch (error) {
		console.error("获取用户列表失败:", error);
		depList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	if (data.applicationTime) {
		data.applicationTime = formatDate(data.applicationTime)
	}
	try {
		if (type === 'update') {
			await OfficeequipmentrepairApi.updateOfficeequipmentrepair(data)
			toast.success('编辑成功');
		} else {
			await OfficeequipmentrepairApi.createOfficeequipmentrepair(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/Officeequipmentrepair/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/Officeequipmentrepair/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>